<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :width="1200"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
  >
    <!--  -->
    <crumbs
      @goBack="goBack"
      :superiorMenu="['设备管理', '设备点巡检', '点巡检方案']"
      marginBottom="10px"
      :currentMenu="jkeForm.title"
    ></crumbs>
    <div class="form-body">
      <a-card title="基本信息" :bordered="false">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="方案编号">
            <a-input
              :disabled="isEdit"
              v-decorator="[
                'programCode',
                {
                  rules: [
                    {
                      required: true,
                      message: '请输入方案编号或自动生成',
                    },
                    {
                      message: '该值不可用，系统中已存在！',
                      validator: (rule, value, callback) =>
                        validateDuplicateValue('mess_device_check_program', 'program_code', value, queryId, callback),
                    },
                  ],
                },
              ]"
              placeholder="请输入"
              :maxLength="16"
            />
            <span v-if="!isEdit" class="btn-text code-btn" @click="genEntityCode">自动生成</span>
          </a-form-item>
          <a-form-item label="方案名称" prop="programName">
            <a-input
              v-decorator="[
                'programName',
                {
                  rules: [{ required: true, message: '请输入方案名称' }],
                },
              ]"
              placeholder="请输入"
              :maxLength="30"
            />
          </a-form-item>
          <a-form-item label="状态">
            <a-select
              v-decorator="['programStatus', { rules: [{ required: true, message: '请选择' }] }]"
              placeholder="请选择"
              allowClear
            >
              <a-select-option value="0">启用</a-select-option>
              <a-select-option value="1">禁用</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-card>
      <a-card title="设备信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="设备类别" prop="deviceCategory">
            <a-select
              :disabled="isEdit"
              placeholder="请选择"
              allowClear
              showSearch
              :filter-option="filterOption"
              @select="selectCustom"
              @change="selectChangeDC"
              v-decorator="['deviceCategory', { rules: [{ required: true, message: '请选择' }] }]"
            >
              <a-select-option v-for="option in deviceCategoryList" :key="option.value" :value="option.value">{{
                option.title
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="点巡检设备" prop="deviceId">
            <a-select
              placeholder="请选择设备类别"
              mode="multiple"
              allowClear
              showSearch
              :filter-option="filterOption"
              @focus="focusDeviceId"
              @change="selectChange"
              v-decorator="['deviceId', { rules: [{ required: true, message: '请选择' }] }]"
            >
              <a-select-option v-for="option in deviceIdList" :key="option.id" :value="option.id"
                >{{ option.deviceCode }}-{{ option.deviceName }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item label=""> </a-form-item>
        </a-form>
      </a-card>
      <a-card title="时间方案" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="方案开始日期">
            <a-date-picker
              :disabled="isEdit"
              v-decorator="['startDate', { rules: [{ required: true, message: '请选择方案开始日期' }] }]"
              style="width: 100%"
              @change="(e) => (startValue = e)"
              :disabled-date="disabledStartDate"
              :default-value="nowDate"
            />
          </a-form-item>
          <a-form-item label="方案结束日期">
            <a-date-picker
              :disabled="isEdit"
              v-decorator="['endDate']"
              style="width: 100%"
              @change="(e) => (endValue = e)"
              :disabled-date="disabledEndDate"
            />
          </a-form-item>
          <a-form-item label=""> </a-form-item>
          <a-form-item label="周期数" prop="periodNum">
            <a-input
              :disabled="isEdit"
              @input="(e) => inputNums(e)"
              v-decorator="[
                'periodNum',
                {
                  rules: [{ required: true, message: '请输入' }],
                },
              ]"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="周期单位" prop="periodUnit">
            <a-select
              :disabled="isEdit"
              placeholder="请选择"
              allowClear
              showSearch
              :filter-option="filterOption"
              v-decorator="['periodUnit', { rules: [{ required: true, message: '请选择' }] }]"
            >
              <a-select-option v-for="option in periodUnitList" :key="option.value" :value="option.value">{{
                option.title
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label=""> </a-form-item>
        </a-form>
      </a-card>
      <a-card title="点巡检项目" :bordered="false" style="margin-top: 12px">
        <j-editable-table
          ref="goodsTable"
          :loading="goodsTable.loading"
          :columns="goodsTable.columns"
          :dataSource="goodsTable.dataSource"
          :maxHeight="300"
          :rowNumber="true"
          :actionButton="true"
          @valueChange="valueChange"
        >
          <template v-slot:action="props">
            <a-popconfirm title="是否删除?" ok-text="是" cancel-text="否" @confirm="handleDeleteGood(props)">
              <span class="del-text">删除</span>
            </a-popconfirm>
          </template>

          <template v-slot:projectCode="props">
            <a-input
              placeholder="请选择"
              :read-only="true"
              @click="showSelect(props)"
              :value="projectNameText(props)"
              :class="projectNameText(props) ? 'has-value' : ''"
            >
              <!-- <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" /> -->
              <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
              <a-icon
                slot="suffix"
                type="close-circle"
                theme="filled"
                class="close-icon"
                @click="getSelectValue(false, '', [], props.rowId)"
              />
            </a-input>
            <tableSelect
              ref="tableSelect"
              @getSelectValue="(id, text, item) => getSelectValue(id, text, item, props.rowId)"
              :key="selectIndex"
            >
              <!-- <div slot="head">我是插槽，写入搜索重置等功能</div> -->
              <div slot="head">
                <div class="uni-card" style="background: #fff">
                  <a-form-model ref="ruleForm" layout="inline" :model="filterForm">
                    <a-form-model-item label="项目编号">
                      <a-input v-model="filterForm.projectCode" placeholder="请输入" />
                    </a-form-model-item>
                    <a-form-model-item label="项目名称">
                      <a-input v-model="filterForm.projectName" placeholder="请输入" />
                    </a-form-model-item>
                    <a-form-model-item>
                      <a-button @click="searchGoods()" type="primary"> 搜索 </a-button>
                      <a-button style="margin-left: 10px" @click="searchResetGoods">重置</a-button>
                    </a-form-model-item>
                  </a-form-model>
                </div>
              </div>
            </tableSelect>
          </template>
        </j-editable-table>
      </a-card>
      <a-card title="其他信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="备注" style="flex: 1">
            <a-textarea placeholder="请输入" :maxLength="500" auto-size v-decorator="['remark']" />
          </a-form-item>
        </a-form>
        <a-form layout="vertical">
          <a-form-item label="附件" style="flex: 1">
            <file-upload :ids="attachment" @getFileList="getFileList"></file-upload>
            <p style="line-height: 30px; color: #8d8d8d">最多上传5个文件，大小不可超过20M</p>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
    <div class="footer-submit form-footer">
      <a-button type="primary" :loading="loadingSubmit" @click="handleSubmit()"> 提交 </a-button>
    </div>
  </jke-modal>
</template>
<script>
import crumbs from '@/components/crumbs.vue'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { getDictModel } from '@/api/goodsManagement'
import { APILX } from '@/api/requestLx'
import { API } from '@/api/requestFzs'
import moment from 'dayjs'
import JEditableTable from '@/components/jeecg/JEditableTable.vue'
import { validateTables, FormTypes, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { fourFloatNum, validateDuplicateValue, checkPrice, integerNum } from '@/utils/util'
import tableSelect from '@/components/tableSelect'
export default {
  data() {
    return {
      jkeForm: {
        title: '新建点巡检方案',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      nowDate: moment().format('YYYY-MM-DD HH:mm:ss'),
      startValue: null,
      endValue: null,
      validateDuplicateValue,
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'programForm' }),
      attachment: '',
      submitApi: APILX.messDeviceCheckProgramAdd,
      isEdit: false,
      loadingSubmit: false,
      deviceCategoryList: [],
      periodUnitList: [], //周期单位
      customerList: [], //客户
      deviceIdList: [], //设备
      goodsTable: {
        loading: false,
        dataSource: [{}],
        columns: [
          {
            title: '项目名称',
            key: 'projectName',
            type: FormTypes.hidden,
          },
          {
            title: '项目Id',
            key: 'itemId',
            type: FormTypes.hidden,
          },
          {
            title: '点巡检项',
            key: 'projectCode',
            type: FormTypes.slot,
            placeholder: '请选择',
            slotName: 'projectCode',
            options: [],
            isrequired: true,
            allowSearch: true,
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '检查标准',
            key: 'checkStandard',
            type: FormTypes.input,
            disabled: true,
            placeholder: '请选择点巡检项',
            slotName: 'checkStandard',
            defaultValue: '',
          },
          {
            title: '操作',
            key: 'action',
            type: FormTypes.slot,
            placeholder: '选择${title}',
            slotName: 'action',
            defaultValue: '',
          },
        ],
      },
      queryId: '', // 校验编号唯一ID
      allGoods: [],
      goodsProps: {},
      selectIndex: 0,
      selectColumns: [
        {
          title: '项目编号',
          align: 'center',
          dataIndex: 'projectCode',
        },
        {
          title: '项目名称',
          align: 'center',
          dataIndex: 'projectName',
        },
        {
          title: '检查标准',
          align: 'center',
          dataIndex: 'checkStandard',
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime',
        },
        // {
        //   title: '创建人',
        //   align: 'center',
        //   dataIndex: 'createByTxt',
        // },
      ],
      filterForm: {},
    }
  },
  components: {
    FileUpload,
    crumbs,
    JEditableTable,
    tableSelect,
  },
  methods: {
    inputNums(v) {
      console.log(v)
      this.$nextTick(() => {
        this.form.setFieldsValue({
          periodNum: integerNum(v.target.value),
        })
      })
    },
    // 限制开始日期
    disabledStartDate(startValue) {
      let date = new Date(new Date().getTime() - 24 * 60 * 60 * 1000)
      const endValue = this.endValue
      if (!startValue || !endValue) {
        return date.valueOf() >= startValue.valueOf()
      }
      return startValue.valueOf() > endValue.valueOf() || date.valueOf() >= startValue.valueOf()
    },
    // 限制结束日期
    disabledEndDate(endValue) {
      let date = new Date(new Date().getTime() - 24 * 60 * 60 * 1000)
      console.log(date, 'ddaattee')
      const startValue = this.startValue
      if (!endValue || !startValue) {
        return date.valueOf() >= endValue.valueOf()
      }
      return startValue.valueOf() >= endValue.valueOf()
    },
    focusDeviceId() {
      // 取deviceCategory值
      let isDC = this.form.getFieldValue('deviceCategory') ? true : false
      if (!isDC) {
        this.$antdMessage.error('请先选择设备类别')
      }
    },
    // 重置
    searchResetGoods() {
      this.filterForm = {}
      this.$refs.tableSelect.searchReset()
    },
    // 筛选
    searchGoods() {
      this.$refs.tableSelect.searchQuery(this.filterForm)
    },
    // 点击选择项目下拉框，弹出选择组件
    showSelect(p) {
      this.goodsProps = p
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [this.goodsProps.rowId] })
        .values[0]
      let par = {
        list: '/mess/messCheckItem/list',
        visible: true, //弹窗开启
        title: '点巡检项目', //标题名称
        multi: false, //是否多选
        columns: this.selectColumns, //表格配置
        value: tableValue.projectCode || '', //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: '项目名称', //回显的中文，如：'张三'
        textKey: 'projectName', //回显的中文key
      }
      this.$refs.tableSelect.getInit(par)
    },
    // 选择项目回调
    getSelectValue(id, text, item, p) {
      this.selectIndex += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      if (!id) {
        this.$refs.goodsTable.setValues([
          {
            rowKey: this.goodsProps.rowId, // 行的id
            values: {
              // 在这里 values 中的 goodsId 是你 columns 中配置的 key
              itemId: '',
              projectCode: '',
              projectName: '',
              checkStandard: '',
            },
          },
        ])
        return
      }
      this.$refs.goodsTable.setValues([
        {
          rowKey: this.goodsProps.rowId, // 行的id
          values: {
            // 在这里 values 中的 goodsId 是你 columns 中配置的 key
            itemId: item[0].id,
            projectCode: `${item[0].projectCode}`,
            projectName: `${item[0].projectName}`,
            checkStandard: item[0].checkStandard,
          },
        },
      ])
      this.setGoodsInfo(id, p)
      console.log(id, text, item, this.goodsProps.rowId, '列表选择的数据')
    },
    // 根据选择的项目带出其他商品信息并填充
    setGoodsInfo(value, p) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false }).values
      var newArr = []
      tableValue.forEach((v) => {
        newArr.push(v.itemId)
      })
      var newArrLen = [...new Set(newArr)].length
      var oldArrLen = tableValue.length
      if (newArrLen < oldArrLen) {
        this.$refs.goodsTable.removeRows(this.goodsProps.rowId)
        this.$antdMessage.warning('该项目已存在')
        return
      }
      this.$refs.goodsTable.getValuesSync({ validate: true })
    },
    // 项目选择框回显值
    projectNameText(p) {
      var item = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [p.rowId] }).values[0]
      return `${item.projectCode ? item.projectCode + '-' : ''}${item.projectName ? item.projectName : ''}`
    },
    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({ entityCode: 'MESS_DEVICE_CHECK_PROGRAM' }).then((res) => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            programCode: res.result,
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    inputPrice(e) {
      this.form.setFieldsValue({
        amount: checkPrice(e.target.value),
      })
    },
    // 下拉搜索
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleDeleteGood(p) {
      this.$refs.goodsTable.removeRows(p.rowId)
      this.selectIndex += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
    },
    valueChange(type) {
      if (type.column.key == 'saleNum') {
        this.$refs.goodsTable.setValues([
          {
            rowKey: type.row.id, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              saleNum: fourFloatNum(type.value),
            },
          },
        ])
      }
      return
      if (type.column.key == 'goodsId') {
        if (!type.value) {
          this.$refs.goodsTable.setValues([
            {
              rowKey: type.row.id, // 行的id
              values: {
                // 在这里 values 中的 specifications 是你 columns 中配置的 key
                basicUnit: '',
                unit: '',
                unitId: '',
              },
            },
          ])
          return
        }
        var goodSelectItem = this.goodsTable.columns[0].options.find((item) => item.value === type.value)
        var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false }).values
        var newArr = []
        tableValue.forEach((v) => {
          newArr.push(v.goodsId)
        })
        var newArrLen = [...new Set(newArr)].length
        var oldArrLen = tableValue.length
        if (newArrLen < oldArrLen) {
          this.$refs.goodsTable.removeRows(type.row.id)
          this.$antdMessage.warning('该商品已存在，请直接修改数据')
          return
        }
        var hasGood = false
        API.findUnitListByGoodsId({ goodsId: type.value }).then((res) => {
          for (let i = 0; i < this.allGoods.length; i++) {
            const item = this.allGoods[i]
            if (item.goodsId == type.value) {
              hasGood = true
            }
          }
          if (!hasGood) {
            this.allGoods.push({
              goodsId: type.value,
              unitList: res.result,
            })
            var unitObj = res.result.find((u) => u.unitType == 'basic_unit')
            this.$refs.goodsTable.setValues([
              {
                rowKey: type.row.id, // 行的id
                values: {
                  // 在这里 values 中的 specifications 是你 columns 中配置的 key
                  basicUnit: 'basic_unit',
                  unit: unitObj.unit || '',
                  unitId: unitObj.id,
                },
              },
            ])
          }
        })
      }
    },
    /* 下拉数据 */
    getGoods() {
      // 字典接口 周期单位
      getDictModel({ dictCode: 'program_period_unit' }).then((res) => {
        this.periodUnitList = res.result
      })
      // 字典接口 设备类别
      getDictModel({ dictCode: 'mess_device_category' }).then((res) => {
        this.deviceCategoryList = res.result
      })
      /* 获取商品下拉数据 */
      API.getAllGoodsBaseInfo({ pageSize: 999, pageNo: 1 }).then((res) => {
        if (res.code == 200) {
          if (res.result.records) {
            this.goodsTable.columns[0].options = []
            res.result.records.forEach((item) => {
              // item.title = item.goodsName
              item.title = `${item.goodsCode ? item.goodsCode + ' | ' : ''}${
                item.goodsName ? item.goodsName + ' | ' : ''
              }${item.spec ? item.spec : ''}`
              item.text = `${item.goodsCode ? item.goodsCode + ' | ' : ''}${
                item.goodsName ? item.goodsName + ' | ' : ''
              }${item.spec ? item.spec : ''}`
              item.value = item.id
              this.goodsTable.columns[0].options.push(item)
            })
          }
          // this.goodsTable.columns[0].options = res.result.records || []
        } else {
          this.$antdMessage.error(res.message)
        }
      })
      // /* 客户下拉 */
      // API.erpCustomerList({ pageSize: 999, pageNo: 1, effectStatus: 'effective' }).then((res) => {
      //   if (res.code == 200) {
      //     this.customSelectList = res.result.records
      //   }
      // })
    },
    /* 选择物料后查询带出物料信息 */
    selectChange(v) {
      if (!v) {
        this.form.setFieldsValue({
          spec: '-',
          basicUnitText: '-',
          typeText: '-',
          categoryText: '-',
          goodsId: '',
        })
        return
      }
    },
    /* 选择类别后查询设备下拉 */
    selectChangeDC(v, arg) {
      if (v) {
        APILX.deviceDeviceList(v).then((res) => {
          if (res.code == 200) {
            console.log(res, 'resres')
            this.deviceIdList = res.result
          }
        })
      }
      if (arg != 1) {
        this.form.setFieldsValue({
          deviceId: undefined,
        })
      }
    },
    selectCustom(v) {
      console.log(v)
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    /* 获取编辑详情 */
    initForm(id) {
      Object.assign(this.$data, this.$options.data.call(this))
      this.jkeForm.visible = true
      this.getGoods()
      if (id) {
        this.queryId = id
        this.jkeForm.title = '编辑点巡检方案'
        this.submitApi = APILX.messDeviceCheckProgramEdit
        this.isEdit = true
        APILX.messDeviceCheckProgramQueryById(id).then((res) => {
          if (res.code == 200) {
            let editForm = res.result
            let deviceId = []
            editForm.messDeviceList.forEach((item) => {
              deviceId.push(item.id)
            })
            this.selectChangeDC(editForm.deviceCategory, 1)
            editForm.deviceId = deviceId
            this.$nextTick(() => {
              this.form.setFieldsValue(editForm)
            })
            this.attachment = res.result.attachment
            let newGoodsList = res.result.messCheckItemList
            for (let i = 0; i < newGoodsList.length; i++) {
              newGoodsList[i].itemId = newGoodsList[i].id
            }
            // this.allGoods = newGoodsList
            this.goodsTable.dataSource = newGoodsList
            console.log(newGoodsList, 'newGoodsList')
          }
        })
      } else {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            programStatus: '0',
            startDate: this.nowDate,
          })
        })
        this.jkeForm.title = '新建点巡检方案'
      }
    },

    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      console.log('上传的附件id：', v)
    },
    // 提交
    handleSubmit() {
      // debugger
      let errArr = []
      let parameters = {}
      let { error, values } = this.$refs.goodsTable.getValuesSync({ validate: true })
      if (error === 0) {
      } else {
        errArr.push(false)
      }
      if (values.length == 0) {
        this.$antdMessage.error('请添加点巡检项目')
        return
      }
      console.log(errArr, 'errArr')
      console.log(values, 'values')
      this.form.validateFields((err, formValues) => {
        console.log(err, 'err')
        console.log(formValues.deviceId, 'formValues')
        let messDeviceCheckProgramDeviceList = []
        formValues.deviceId.forEach((item) => {
          messDeviceCheckProgramDeviceList.push({
            deviceId: item,
          })
        })
        if (!err) {
          if (formValues.startDate) {
            formValues.startDate = moment(formValues.startDate).format('YYYY-MM-DD HH:mm:ss')
          }
          if (formValues.endDate) {
            formValues.endDate = moment(formValues.endDate).format('YYYY-MM-DD HH:mm:ss')
          }
          parameters = {
            ...formValues,
            attachment: this.attachment,
            messDeviceCheckProgramDeviceList: messDeviceCheckProgramDeviceList,
          }
          if (this.isEdit) {
            parameters.id = this.queryId
          }
          // let messDeviceCheckProgramDeviceList = []
          // console.log(formValues.deviceId,'formValues.deviceId');
          if (errArr.length == 0) {
            console.log(values, 'values')
            let messDeviceCheckProgramItemList = values.map((g, i) => {
              return {
                itemId: g.itemId,
              }
            })
            parameters.messDeviceCheckProgramItemList = messDeviceCheckProgramItemList
            console.log(parameters, '0.0.0.parameters')
            this.loadingSubmit = true
            this.submitApi(parameters).then((res) => {
              this.loadingSubmit = false
              if (res.code == 200) {
                let subMsg = this.isEdit ? '点巡检方案编辑成功！' : '点巡检方案新建成功！'
                this.$antdMessage.success(subMsg)
                this.$emit('refresh')
                this.goBack()
              } else {
                this.$antdMessage.error(res.message)
              }
            })
          } else {
            this.$antdMessage.error('点巡检项目不能为空！')
          }
        } else {
        }
      })
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
/deep/.ant-form-vertical {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
</style>
